package com.briup.estore.web.servlet;

import com.briup.estore.bean.Customer;
import com.briup.estore.service.CustomerService;
import com.briup.estore.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 登录逻辑
 */
@WebServlet("/userLogin")
public class LoginServlet extends HttpServlet {
    private CustomerService customerService;

    {
        customerService = new CustomerServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取参数值
        String username = req.getParameter("name");
        String password = req.getParameter("password");
        // 2. 调用service
        Customer user = customerService.login(username, password);
        // 记录一下当前登录的用户是谁
        HttpSession session = req.getSession();

        // 3. 分发页面
        if (user == null) {
            session.setAttribute("msg", "登录失败，请重新登录");
            resp.sendRedirect("login");
        } else {
            session.setAttribute("msg", "登录成功");
            session.setAttribute("user", user);
            // cookie里放一份
            Cookie cookie = new Cookie("userId", user.getId() + "");
            // 设置七天有效
            cookie.setMaxAge(3600 * 24 * 7);
            resp.addCookie(cookie);
            resp.sendRedirect("index_data");
        }
    }
}
